With \( \alpha = 0.1 \), the updates would increase \( \theta_0, \theta_1, \theta_2 \) and decrease \( \theta_3 \), nudging \( \hat{y} \) upward toward the target \( y = 2 \).
Linear regression is where the mechanics of optimisation become visible. The model itself is trivial — a weighted sum of features — which is exactly why it is the right place to learn how a model is actually fitted, a process that carries directly into logistic regression and neural networks later in the course.
There are two routes to the optimal parameters. The normal equation solves for them in closed form, elegantly and in one step, but requires inverting a matrix whose cost grows cubically with the number of features. Gradient descent reaches the same answer iteratively, and scales. We develop both, starting with the MSE cost function, moving from the single-feature case to the fully vectorised multi-variable form, and then dealing with the practical questions gradient descent forces on you: choosing the learning rate α, why feature scaling is not optional here, and when to stop.
The goal of linear regression is to model the relationship between one or multiple features and a continuous target variable. Given data points \( (x_1, y_1), (x_2, y_2), \ldots, (x_m, y_m) \), we find a line (or hyperplane) that "best fits" the data.
Suppose we want to predict a car's fuel efficiency (miles per gallon) based on how heavy the car is. A learned model might have:
| Pounds (in 1000s) | Miles per Gallon |
|---|---|
| 3.50 | 18 |
| 3.69 | 15 |
| 3.44 | 18 |
| 3.43 | 16 |
| 4.34 | 15 |
| 4.42 | 14 |
| 2.37 | 24 |
A model that predicts gas mileage could additionally use features such as engine displacement (\( x_2 \)), acceleration (\( x_3 \)), number of cylinders (\( x_4 \)), and horsepower (\( x_5 \)). The equation becomes:
Once the model form is fixed, the remaining task is to find the parameter values that fit the data best. There are two ways to do this, and the rest of the chapter develops both:
To measure how "wrong" our predictions are, we use the Mean Squared Error (MSE), also known as the squared loss. For a model with parameters \( \theta \) (where \( \theta_0 = b \) is the bias and \( \theta_1, \ldots \) are weights):
The \( \frac{1}{2} \) factor is a convenience that cancels the 2 from differentiation (you will see this shortly). Minimizing \( \frac{1}{2} \text{MSE} \) is equivalent to minimizing MSE — the optimal \( \theta \) is the same.
Let \( X \) be the \( m \times (p+1) \) design matrix (with a column of 1's prepended for the bias), \( \theta \) the \( (p+1) \times 1 \) parameter vector, and \( y \) the \( m \times 1 \) target vector. Predictions are \( \hat{y} = X\theta \), and MSE becomes:
Here \( (X\theta - y)^T \) is \( 1 \times m \), \( (X\theta - y) \) is \( m \times 1 \), and their product is a \( 1 \times 1 \) scalar — exactly like the sum of squared residuals.
To find the \( \theta \) that minimizes \( J(\theta) \), we take the derivative with respect to \( \theta \), set it to zero, and solve algebraically.
Rearranging gives the Normal Equation:
| Drawback | Explanation |
|---|---|
| Computational Complexity | Matrix inversion is \( O(n^3) \). For \( n = 10{,}000 \) features, ~1 trillion operations! |
| Non-Invertible Matrix | \( X^T X \) might be singular if features are linearly dependent or \( m \lt p \). |
| Memory Requirements | Must store the entire dataset in memory; \( X^T X \) is \( (p+1) \times (p+1) \). |
| No Generalization | Only works for this specific problem — cannot extend to NNs, logistic regression, etc. |
Gradient Descent is a mathematical technique that iteratively finds the weights and bias that produce the model with the lowest loss. The model begins with randomized weights and biases (usually near zero), then repeats the following process:
For the simple model \( h_\theta(x) = \theta_0 + \theta_1 x \), we need the partial derivatives of \( J \) with respect to both \( \theta_0 \) and \( \theta_1 \).
The update rules (simultaneous update!) are:
The multivariate case is a direct extension. With \( h_\theta(x) = \theta^T x = \sum_{j=0}^{p-1} \theta_j x_j \) (where \( x_0 = 1 \)):
In matrix form, the entire gradient vector is:
And the compact vectorized update:
The previous sections derived the updates for the linear regression cost specifically. It is worth stating the algorithm once in general form, since the same loop is used later for logistic regression and for neural networks. The following sections then work through the multi-variable case in more detail, including a numerical example.
Goal: Minimize the scalar function \( f(\theta) \).
Hyperparameters: Number of epochs \( N \), learning rate \( \eta \).
For the multi-variable linear hypothesis \( h_\theta(x) = \theta_0 + \theta_1 x_1 + \cdots + \theta_{p-1} x_{p-1} = \theta^T x \) (with \( x_0 = 1 \)) and MSE cost:
Defining the error per example \( e_i = \theta^T x_i - y_i \), we differentiate through the chain rule:
So the per-parameter gradient is:
In compact matrix notation, the whole gradient vector becomes:
And the simultaneous vectorized update:
Consider the first row of a 4-column dataset (bias column \( x_0 = 1 \), then 3 real features). Assume all four weights are initialized to \( \theta_0 = \theta_1 = \theta_2 = \theta_3 = 0.59 \), true label \( y = 2 \), and we are processing a batch of size 1 for simplicity.
| \( x_0 \) | \( x_1 \) | \( x_2 \) | \( x_3 \) | \( \hat{y} = \theta^T x \) | \( y \) | \( e = \hat{y} - y \) | \( \partial J/\partial \theta_0 \) | \( \partial J/\partial \theta_1 \) | \( \partial J/\partial \theta_2 \) | \( \partial J/\partial \theta_3 \) |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1.5 | 2 | -1.2 | 1.65 | 2 | -0.35 | -0.35 · 1 | -0.35 · 1.5 | -0.35 · 2 | -0.35 · (-1.2) |
With \( \alpha = 0.1 \), the updates would increase \( \theta_0, \theta_1, \theta_2 \) and decrease \( \theta_3 \), nudging \( \hat{y} \) upward toward the target \( y = 2 \).
Gradient descent updates parameters by taking steps proportional to the slope of the cost function. The step size is controlled by the hyperparameter \( \alpha \) (learning rate).
When features have very different scales, the cost surface becomes stretched in some directions and narrow in others. Gradient descent then takes very small steps along one axis and oscillates along another, so it converges slowly.
Without scaling:
Solution: Scale all features to comparable ranges (e.g., 0–1 min-max or standardized z-scores).
Gradient descent does not stop on its own, so we need an explicit stopping rule. Three are commonly used, and they are often combined:
| Strategy | How it Works |
|---|---|
| Cost-Change Threshold | Stop when \( |J(t) - J(t-1)| < \varepsilon \), e.g., \( \varepsilon = 10^{-6} \) |
| Fixed Iterations | Run for a set number of epochs, say 1000 (simplest, but may waste compute or under-converge) |
| Validation Performance | Stop when validation error starts increasing → Early Stopping (prevents overfitting!) |
| Gradient Magnitude | Stop when \( \|\nabla J\| < \varepsilon \) — the gradient itself is nearly zero |
A fitted regression model for house price (in $1000s) on house size (in 100s of sq ft) is: \( \hat{y} = 50 + 35x \). Click to reveal interpretations.
A. Interpret the intercept \( \theta_0 = 50 \).
B. Interpret the slope \( \theta_1 = 35 \).
C. Predict the price of a 1,500 sq ft house. (Watch units! \( x \) is in 100s of sq ft.)
For each scenario, pick the better approach: Normal Equation or Gradient Descent.
A. 500 training examples, 3 features, need answer quickly for a statistics homework.
B. 5,000,000 training examples, 500 features, training on GPU with TensorFlow.
A student writes the following update step. What's wrong?
temp0 = θ0 − α · dJ/dθ0
θ0 = temp0
temp1 = θ1 − α · dJ/dθ1 ← dJ/dθ1 uses the ALREADY-UPDATED θ0
θ1 = temp1
Given \( X \in \mathbb{R}^{500 \times 20} \) (with bias column), \( \theta \in \mathbb{R}^{20 \times 1} \), \( y \in \mathbb{R}^{500 \times 1} \).
A. What are the dimensions of the prediction vector \( \hat{y} = X\theta \)?
B. What are the dimensions of the residual \( X\theta - y \) and of the full gradient \( \nabla J(\theta) \)?
Given one training example \( (x = 2, y = 7) \), current parameters \( \theta_0 = 1 \), \( \theta_1 = 2 \), and learning rate \( \alpha = 0.1 \).
Step 1: Compute the prediction \( \hat{y} = h_\theta(x) \).
Step 2: Compute the error \( \hat{y} - y = 5 - 7 = -2 \).
Step 3: Compute gradients (with \( m = 1 \)):
Step 4: Apply the simultaneous update with \( \alpha = 0.1 \):
Notice that the error was negative (we under-predicted), so both parameters move in the positive direction, which is the correct "uphill" push to raise predictions closer to \( y = 7 \).
Compute \( \frac{1}{2} \text{MSE} \) (i.e., \( J(\theta) \)) for the dataset:
| i | \( x_i \) | \( y_i \) | \( \hat{y}_i = 1 + 2x_i \) |
|---|---|---|---|
| 1 | 1 | 4 | 3 |
| 2 | 2 | 7 | 5 |
| 3 | 3 | 8 | 7 |
Step 1: Compute residuals \( r_i = \hat{y}_i - y_i \):
Step 2: Sum of squared residuals:
Step 3: Divide by \( 2m = 6 \):
Design matrix \( X \) (with bias column): \( X = \begin{bmatrix} 1 & 1 & 2 \\ 1 & 2 & 4 \\ 1 & 3 & 6 \end{bmatrix} \). Column 3 is exactly 2 × Column 2.
Step 1: Recognize linear dependence. Column 3 = 2 · Column 2.
Step 2: Conclude \( X^T X \) is singular (non-invertible).
Step 3: Remedies:
Mini-batch of 3 examples, 2 real features + bias column (p = 3):
Step 1: Predictions \( \hat{y} = X\theta \):
Step 2: Residual \( \hat{y} - y \):
Step 3: \( X^T (\hat{y} - y) \) (pre-factor):
Step 4: Divide by \( m = 3 \):
Two features predicting house price: size in sq ft (\( x_1 \in [500, 5000] \)) and bedrooms (\( x_2 \in [1, 5] \)). A GD step updates: \( \theta_1 := \theta_1 - \alpha \cdot 4000 \), \( \theta_2 := \theta_2 - \alpha \cdot 0.1 \).
Diagnosis: The gradient for \( \theta_1 \) is 40,000× larger than for \( \theta_2 \), so \( \theta_1 \) moves drastically while \( \theta_2 \) creeps. A single α cannot serve both well.
Fix — Standardize both features:
After standardization, \( \mu = 0 \) and \( \sigma = 1 \) for both features. Now both gradients are on the same scale and a single well-chosen α works for all parameters.
With \( m = 2 \) examples: \( (x=1, y=3) \) and \( (x=3, y=7) \). Current parameters: \( \theta_0 = 0 \), \( \theta_1 = 1 \). Learning rate \( \alpha = 0.05 \).
Predictions: \( \hat{y}_1 = 0 + 1(1) = 1 \), \( \hat{y}_2 = 0 + 1(3) = 3 \).
Residuals: \( r_1 = 1 - 3 = -2 \), \( r_2 = 3 - 7 = -4 \).
A dataset has \( m = 1200 \) training examples and \( p = 8 \) features (plus the bias column). State the dimensions of:
Match each GD behavior (left) to the likely learning-rate issue (right):
Answers pool: (a) α too small, (b) α well-tuned, (c) α too large / diverging
From Problem 4 in Section 4, you found \( \nabla J(\theta) = [2/3,\ 2,\ 8/3]^T \). Starting \( \theta = [0, 1, 1]^T \), apply one gradient-descent step with \( \alpha = 0.1 \). Give the updated \( \theta \).
A training run plots J(θ) vs. epoch. For each scenario, suggest which stopping strategy (or strategies) from Section 2.7 would be most appropriate and why.
Answer all 8 questions. Click an option for instant feedback.
Your score: 0 / 8